package com.ruoyi.chat.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.chat.service.ICharService;
import com.ruoyi.common.core.domain.AjaxResult;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.wav.WavFileReader;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.vosk.LibVosk;
import org.vosk.LogLevel;
import org.vosk.Model;
import org.vosk.Recognizer;

import javax.sound.sampled.AudioSystem;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;

/**
 * @program: RuoYi-Vue-master
 * @description:
 * @author: xgw
 * @create: 2025-01-11 09:07
 **/


@Service
public class CharServiceImpl implements ICharService {


    /** 音频识别出文字的api
    * @Description:
    * @Param: [userId, file]
    * @return: com.ruoyi.common.core.domain.AjaxResult
    * @Author: xgw
    * @Date: 2025/1/14
    */
    @Override
    public String charWithVideo(String userId, String videoPath) {
            String userSpeech = "";
            LibVosk.setLogLevel(LogLevel.DEBUG);
            //语音文件仅支持wav
            File file = new File(videoPath);
//            File file = new File("C:\\Users\\xgw\\Desktop\\RuoYi-Vue-master\\RuoYi-Vue-master\\ruoyi-admin\\src\\main\\java\\com\\ruoyi\\testVideo\\01.wav");
            try (Model model = new Model("D:\\server\\vosk-model-small-cn-0.22\\vosk-model-small-cn-0.22"); //模型地址
                 //模型地址
                 InputStream ais = AudioSystem.getAudioInputStream(new BufferedInputStream(new FileInputStream(file)));
                 Recognizer recognizer = new Recognizer(model, getSampleRate(file))) {
                // 开启词信息的详细输出
                 recognizer.setWords(true);
                 int bytes;
                //缓存大小：4k
                 byte[] b = new byte[4096];
                 while ((bytes = ais.read(b)) >= 0) {
                     //得到文字大小
                     recognizer.acceptWaveForm(b, bytes);
                 }
                userSpeech = recognizer.getFinalResult();
             } catch (Exception e) {
                 e.printStackTrace();
             }
        // 使用 JSONObject 解析 userSpeech 中的 JSON 字符串
        String query = null;
        // 确保 userSpeech 是有效的 JSON 格式
        if (!userSpeech.isEmpty()) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                JsonNode rootNode = mapper.readTree(userSpeech);  // 将字符串解析为 JSON 对象
                // 获取 'text' 字段的值
                String text = rootNode.path("text").asText();
                System.out.println("提取的文本内容：" + text);
                return text;  // 返回提取的文本
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return "未找到内容";
    }



    private static  Float getSampleRate(File file) throws Exception {
        WavFileReader fileReader = new WavFileReader();
        AudioFile audioFile = fileReader.read(file);
        String sampleRate = audioFile.getAudioHeader().getSampleRate();
        String channel = audioFile.getAudioHeader().getChannels();
        System.out.println("语音的声道：" + channel );
        System.out.println("语音的采样率：" + sampleRate);
        return Float.parseFloat(sampleRate) * Integer.parseInt(channel);
    }
}
